#include "CSessionSocketClient.h"
#include "apiSessionSocketClient.h"
REGISTESOCKETCLIENT(CSessionSocketClient, SOCKETCLIENT_TYPE_SESSION, true);

unsigned int id = 0;
CSessionSocketClient::CSessionSocketClient()
{
}

CSessionSocketClient::~CSessionSocketClient()
{
}
bool CSessionSocketClient::PreAccept()
{
	m_sckDes.hostId = _InterlockedIncrement(&id);
	return true;
}
void CSessionSocketClient::OnRead(int errCode)
{
	CSocketClient::OnRead(errCode);
}

void CSessionSocketClient::OnSend(int errCode) {
	CSocketClient::OnSend(errCode);
}

bool GetHostInfo(void* hSocketClient, HOSTINFOOBJ& serverInfo)
{
	CSessionSocketClient* client = GETSOCKETCLIENT(CSessionSocketClient, hSocketClient);
	if (client != nullptr)
	{
		serverInfo.hostId = client->m_sckDes.hostId;
		if ((client->m_sckDes.dataSize > sizeof(int)) && client->m_sckDes.data)
		{
			int nSerialNumber;
			memcpy(&nSerialNumber, client->m_sckDes.data, sizeof(int));
			if (nSerialNumber > 0 && nSerialNumber < client->m_sckDes.dataSize - sizeof(int))
			{
				memcpy(serverInfo.serialNumber, (char*)client->m_sckDes.data + sizeof(int), nSerialNumber);
				serverInfo.serialNumber[nSerialNumber % sizeof(serverInfo.serialNumber)] = 0;
				if (client->m_sckDes.dataSize > nSerialNumber + sizeof(int) + 2 * sizeof(WCHAR))
					for (WCHAR* s = (WCHAR*)((char*)client->m_sckDes.data + sizeof(int) + nSerialNumber); *s; s += wcslen(s) + 1)
					{
						char cDrivers[16];
						sprintf_s(cDrivers, "%ws", s);
						std::string strDriver(cDrivers);
						serverInfo.lstDrivers.push_back(strDriver);
					}
			}
			char* ip = inet_ntoa(client->m_pSocketObj->addrClient.sin_addr);
			if (ip)
			{
				memcpy(serverInfo.ip, ip, strlen(ip));
			}
			else {
				memcpy(serverInfo.ip, "Unknown Ip", strlen("Unknown Ip"));
			}
			return true;
		}
	}
	return false;
}

bool SendCommand(void* hSocketClient,int clientType)
{
	CSessionSocketClient* client = GETSOCKETCLIENT(CSessionSocketClient, hSocketClient);
	if (client != nullptr)
	{
		bool bSend = false;
		SOCKETDESOBJ socketDesObj;
		socketDesObj.hostId = client->m_iId;
		socketDesObj.desType = clientType;
		socketDesObj.dataSize = 0;
		socketDesObj.data = nullptr;
		char* data = new char[sizeof(SOCKETDESOBJ) + socketDesObj.dataSize];
		memcpy(data, &socketDesObj, sizeof(SOCKETDESOBJ));
		if (!(bSend = client->SendDataToQueue(data, sizeof(SOCKETDESOBJ) + socketDesObj.dataSize)))
		{
			delete[] data;
		}
		delete[] socketDesObj.data;
		return bSend;
	}
	return false;
}

bool SendScreenCatchCommand(void* hSocketClient)
{
	return SendCommand(hSocketClient, SOCKETCLIENT_TYPE_SCREENCATCH);
}

bool SendScreenControlCommand(void* hSocketClient)
{
	return SendCommand(hSocketClient, SOCKETCLIENT_TYPE_SCREENCONTROL);
}